package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.mapper.targetSystem.external.SystemExternalMapper;
import com.xinchuang.entity.targetSystem.system.*;
import com.xinchuang.entity.targetSystem.target.TargetData;
import com.xinchuang.entity.targetSystem.target.TargetIndexList;
import com.xinchuang.entity.targetSystem.target.TargetInfo;
import com.xinchuang.service.targetSystem.ArchitectureService;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName ArchitectureServiceImpl
 * @Description: TODO(体系新增需求实现)
 * @Author zhangxuan
 * @Date 2021-05-13 10:30
 * @Verion V1.0
 */
@Service(value = "architectureService")
public class ArchitectureServiceImpl implements ArchitectureService {

    @Resource
    private SystemExternalMapper system;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private KeyWordSystem keyWordSystem;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);

    @Override
    public Result selectIndexPull(String sysId) {
        List<InfoElement> list = system.selectSysInfoDataList(sysId);
        if (null != list && !list.isEmpty()) {
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (InfoElement infoElement : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("label", infoElement.getValue());
                map.put("value", infoElement.getKey());
                resultList.add(map);
            }
            return ResultUtil.success("查询成功", resultList);
        }
        return ResultUtil.success("查询成功", new ArrayList<>());
    }

    @Override
    public Result selectSystemWaitList(int pageNum, int pageSize, String sysId, String index) {
        if (StringUtils.isBlank(sysId)) {
            return ResultUtil.error(ResultEnum.EXTERNAL_RAPEX_EMPTY);
        }
        if (StringUtils.isNotBlank(index)) {
            return getInitSystemWaitDataListByIndex(pageNum, pageSize, sysId, index);
        }
        return getInitSystemWaitDataList(pageNum, pageSize, sysId);
    }

    @Override
    public Result selectSystemIndexList(String sysId) {
        return getInitSystemWaitDataList(sysId);
    }

    @Override
    public Result insertConfirmIndex(List<SystemsRelation> list, String sysId, String status) {
        if (null == list || list.isEmpty()) {
            return ResultUtil.error(ResultEnum.UPDATE_EMPTY);
        }
        String indexKey = keyWordSystem.getVERSION() + "index" + sysId;
        List<String> targetList = new ArrayList<>();
        for (SystemsRelation systemsRelation : list) {
            systemsRelation.setSysId(sysId);
            systemsRelation.setSysRelId(snowflakeIdWorker.nextId() + "");
            targetList.add(systemsRelation.getTargetId());
        }
        if (status.equals("add")) {
            system.insertSystemsRelation(list);
        }
        List<TargetInfo> targetInfos = system.selectConfirmIndexList(targetList);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (null != targetInfos && !targetInfos.isEmpty()) {
            for (TargetInfo targetInfo : targetInfos) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", targetInfo.getName() + "(" + targetInfo.getKey() + ")");
                map.put("value", targetInfo.getValue());
                if (redisUtil.hasKey(indexKey + targetInfo.getKey())) {
                    Double index = (Double) redisUtil.get(indexKey + targetInfo.getKey());
                    if (index == 0) {
                        map.put("index", 0);
                    } else if (targetInfo.getValue() >= index) {
                        map.put("index", 100);
                    } else {
                        map.put("index", (int) (targetInfo.getValue() / index * 100));
                    }
                } else {
                    map.put("index", 0);
                }
                resultList.add(map);
            }
        }
        return ResultUtil.success("添加成功", resultList);
    }

    @Override
    public Result selectSystemConfirmList(int pageNum, int pageSize, String sysId, String index, Integer taskId) {
        return getInitSystemContirmDataList(pageNum, pageSize, sysId, index, taskId);
    }

    /**
     * 查询待选目标指标排序列表
     */
    public Result getInitSystemWaitDataListByIndex(int pageNum, int pageSize, String sysId, String index) {
        SystemsMaster systemsMaster = system.selectSystemsOnlyGetTypeIdBySId(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_RAPEX_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //根据类别查询目标
        List<String> typeIds = null;
        if (StringUtils.isNotBlank(systemsMaster.getIncludeType())) {
            typeIds = new ArrayList<>();
            if (systemsMaster.getIncludeType().contains(",")) {
                typeIds.addAll(Arrays.asList(systemsMaster.getIncludeType().split(",")));
            } else {
                typeIds.add(systemsMaster.getIncludeType());
            }
        }
        if (CollectionUtil.isEmpty(typeIds)) {
            resultMap.put("waitList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        //筛选已经选择的目标
        List<String> confirmTarget = system.selectSystemsRelationTargetId(sysId);
        if (null == confirmTarget || confirmTarget.isEmpty()) {
            confirmTarget = null;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetIndexList> targetIndexLists = system.selectSysWaitDataList(typeIds, confirmTarget, index, sysId);
        PageInfo<TargetIndexList> pageInfo = new PageInfo<>(targetIndexLists);
        resultMap.put("waitList", pageInfo.getList());
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    /**
     * 初始化待选系统详细信息列表
     */
    private Result getInitSystemWaitDataList(int pageNum, int pageSize, String sysId) {
        SystemsMaster systemsMaster = system.selectSystemsOnlyGetTypeIdBySId(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_RAPEX_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //根据类别查询目标
        List<String> typeIds = null;
        if (StringUtils.isNotBlank(systemsMaster.getIncludeType())) {
            typeIds = new ArrayList<>();
            if (systemsMaster.getIncludeType().contains(",")) {
                typeIds.addAll(Arrays.asList(systemsMaster.getIncludeType().split(",")));
            } else {
                typeIds.add(systemsMaster.getIncludeType());
            }
        }
        if (CollectionUtil.isEmpty(typeIds)) {
            resultMap.put("waitList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        //筛选已经选择的目标
        List<String> confirmTarget = system.selectSystemsRelationTargetId(sysId);
        if (null == confirmTarget || confirmTarget.isEmpty()) {
            confirmTarget = null;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetData> targetDataList = system.selectWaitChoiceTarget(typeIds, confirmTarget, null);
        PageInfo<TargetData> pageInfo = new PageInfo<>(targetDataList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            for (TargetData targetData : pageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("indexData", 0);
                map.put("typeName", system.selectTargetTypeByTargetId(targetData.getTargetId()));
                map.put("hitDegree", null);
                list.add(map);
            }
        }
        resultMap.put("waitList", list);
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    /**
     * 查询能力指标列表
     */
    private Result getInitSystemWaitDataList(String sysId) {
        String indexKey = keyWordSystem.getVERSION() + "index" + sysId;
        Map<String, Object> resultMap = new HashMap<>();
        SystemsMaster systemsMaster = system.selectSystemsOnlyGetTypeIdBySId(sysId);
        resultMap.put("systemsName", systemsMaster.getSystemsName());
        List<String> indexList = system.selectSysInfoList(sysId);
        if (null == indexList || indexList.isEmpty()) {
            resultMap.put("indexList", new ArrayList<>());
        } else {
            List<String> typeIds = system.selectSystemsTargetTypes(sysId);
//            if (StringUtils.isNotBlank(systemsMaster.getIncludeType())) {
//                typeIds = new ArrayList<>();
//                if (systemsMaster.getIncludeType().contains(",")) {
//                    typeIds.addAll(Arrays.asList(systemsMaster.getIncludeType().split(",")));
//                } else {
//                    typeIds.add(systemsMaster.getIncludeType());
//                }
//            }
            List<InfoElement> infos = system.selectSysInfoDataList(sysId);
            List<String> info = new ArrayList<>();
            if (null != infos && !infos.isEmpty()) {
                for (InfoElement infoElement : infos) {
                    info.add(infoElement.getKey());
                }
            }
            if (CollectionUtil.isNotEmpty(typeIds) &&
                    CollectionUtil.isNotEmpty(infos)) {
                List<TargetInfo> data = system.selectInfoAll(typeIds, info);
                if (null != data && !data.isEmpty()) {
                    List<Map<String, Object>> resultList = new ArrayList<>();
                    for (InfoElement infoElement : infos) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", infoElement.getValue());
                        boolean juage = false;
                        for (TargetInfo datum : data) {
                            if (infoElement.getKey().equals(datum.getKey())) {
                                map.put("number", datum.getValue());
                                map.put("index", 100);
                                map.put("value", 0);
                                juage = true;
                                break;
                            }
                        }
                        if (!juage) {
                            map.put("number", 0);
                            map.put("index", 0);
                            map.put("value", 0);
                        }
                        if (redisUtil.hasKey(indexKey + infoElement.getKey())) {
                            redisUtil.del(indexKey + infoElement.getKey());
                        }
                        redisUtil.set(indexKey + infoElement.getKey(), map.get("value"), KeyWordSystem.REDIS_TIME);
                        resultList.add(map);
                    }
                    resultMap.put("indexList", resultList);
                } else {
                    resultMap.put("indexList", new ArrayList<>());
                }
            } else {
                resultMap.put("indexList", new ArrayList<>());
            }
        }
        return ResultUtil.success("查询成功", resultMap);
    }

    /**
     * 初始化已选系统详细信息列表
     */
    private Result getInitSystemContirmDataList(int pageNum, int pageSize, String sysId, String index, Integer taskId) {
        SystemsMaster systemsMaster = system.selectSystemsOnlyGetTypeIdBySId(sysId);
        if (null == systemsMaster) {
            return ResultUtil.error(ResultEnum.EXTERNAL_RAPEX_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        //筛选已经选择的目标
        List<String> confirmTarget = system.selectSystemsRelationTargetId(sysId);
        if (CollectionUtil.isEmpty(confirmTarget)) {
            resultMap.put("confirmList", new ArrayList<>());
            resultMap.put("pageNum", pageNum);
            resultMap.put("pageSize", pageSize);
            resultMap.put("total", 0);
            resultMap.put("pageAll", 0);
            return ResultUtil.success("查询成功", resultMap);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TargetIndexList> targetIndexLists = null;
        if (null == taskId) {
            targetIndexLists = system.selectSysConfirmDataList(confirmTarget, index, sysId);
        } else {
            targetIndexLists = system.selectSysConfirmDataListByTask(confirmTarget, index, sysId);
        }
        PageInfo<TargetIndexList> pageInfo = new PageInfo<>(targetIndexLists);
        resultMap.put("confirmList", pageInfo.getList());
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

}